package fr.umlv.m2.jee.spij.web.file.upload;

import java.io.Serializable;
import java.util.Locale;

/**
 * Define a File which is prepared to be uploaded
 *
 * @author Christophe Chillan
 */
public class FileUploaded implements Serializable {

    private String name;

    private String mime;

    private long length;

    public FileUploaded() {

    }

    public FileUploaded(byte[] data, String name) {
        this.length = data.length;
        this.name = name;
        makeMime(name);
    }

    /**
     * Gets the name of the file.
     *
     * @return the name of the file
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the name of the file.
     *
     * @param name
     */
    public void setName(String name) {
        this.name = name;
        int extDot = name.lastIndexOf('.');
        if (extDot > 0) {
            String extension = name.substring(extDot + 1);
            mime = MimeType.valueOf(extension.toUpperCase(Locale.getDefault())).type();
        }
    }


    private void makeMime(String name) {
        int extDot = name.lastIndexOf('.');
        if (extDot > 0) {
            String extension = name.substring(extDot + 1);
            mime = MimeType.valueOf(extension.toUpperCase(Locale.getDefault())).type();
        }
    }

    /**
     * Gets the length of the file.
     *
     * @return the size of the file
     */
    public long getLength() {
        return length;
    }

    /**
     * Sets the length of the file.
     *
     * @param length
     */
    public void setLength(long length) {
        this.length = length;
    }

    /**
     * Gets the MIME type of the file.
     *
     * @return the MIME type
     *
     * @see MimeType
     */
    public String getMime() {
        return mime;
    }

    /**
     * @see Object
     */
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("file name : ").append(name).append("\n");
        builder.append("type mime : ").append(mime).append("\n");
        builder.append("file length : ").append(length).append("\n");
        return super.toString();
    }

}
